import {FlatList, StyleSheet, TouchableOpacity, View} from 'react-native';
import {
  Avatar,
  Empty,
  Header,
  Img,
  ObserverButton,
  ObserverText,
  ObserverView,
  toLink,
} from '../../components';
import {
  CreateOrder,
  PayTypeConfig,
  ProductList,
  UserAssets,
} from '../../services';
import {useEffect, useState} from 'react';
import {
  dpw10,
  dpw12,
  dpw16,
  dpw24,
  dpw4,
  dpw40,
  dpw48,
  dpw6,
  dpw66,
  dpw8,
} from '../../constants';
import {observer} from 'mobx-react-lite';
import {useGlobalStore, useUserInfoStore} from '../../mobx';
import coinPng from '../../assets/img/common/coin.png';
import ModalHeader from './ModalHeader';
import ProductItem from './Product';

const list = [
  {id: 'userinfo'},
  {id: 'topay'},
  {id: 'vip-topay'},
  {id: 'topay-type'},
  {id: 'kind-tips'},
];

const kindTips = [
  {id: 1, text: 'payTip1'},
  {id: 2, text: 'payTip2'},
  {id: 3, text: 'payTip3'},
  {id: 4, text: 'payTip4'},
  {id: 5, text: 'payTip5'},
];

interface ReadProps {
  Id: number;
  Name: string;
  Description: string;
  Price: number;
  Oprice: number;
  Score: number;
  PresentScore: number;
  FpresentScore: number;
  ImageUrl: string;
  IsHot: boolean;
  IsSell: boolean;
  IsRecommend: boolean;
  BaseDescribe: string;
  DetailDescribe: string;
}

const ToPay = observer((props: any) => {
  const {navigation, route} = props;
  const {userInfo} = useUserInfoStore();
  const {appConfig} = useGlobalStore();
  const [{amont, pId}, setAmont] = useState({amont: 0, pId: -1});
  const [coin, setCoin] = useState(0);
  const [{Read, VIP}, setProductList] = useState<{
    Read: ReadProps[];
    VIP: ReadProps[];
  }>({
    Read: [],
    VIP: [],
  });
  const [payTypes, setPayTypes] = useState([]);
  const [payTypeId, setPayTypeId] = useState(-1);

  useEffect(() => {
    if (userInfo?.Token) {
      PayTypeConfig({Type: 1, UT: userInfo?.Token})
        .then((res: any) => {
          setPayTypes(res?.Data);
        })
        .catch(() => {});
    }
  }, [userInfo?.Token]);

  useEffect(() => {
    if (userInfo?.Token) {
      ProductList({MallType: 1, UT: userInfo?.Token})
        .then((res: any) => {
          setProductList(res?.Data);
          setAmont({
            amont: res?.Data?.Read[0]?.Price,
            pId: res?.Data?.Read[0]?.Id,
          });
        })
        .catch(() => {});
    }
  }, [userInfo?.Token]);

  useEffect(() => {
    if (userInfo?.Token) {
      UserAssets({UT: userInfo?.Token})
        .then((res: any) => {
          setCoin(res?.Data?.Coins);
        })
        .catch(() => {});
    }
  }, [userInfo?.Token]);

  const toServerUrl = () => {
    if (userInfo?.Token) {
      toLink(
        `${appConfig?.OnlineCustomerUrl}&uid=${userInfo?.GameId}&name=PPMH_${userInfo?.Account}&avatar=${userInfo?.HeadImg}`,
      );
    }
  };

  const onSelectPay = (info: ReadProps) => {
    if (info.Id !== pId) {
      setAmont({
        amont: info.Price,
        pId: info.Id,
      });
    }
  };

  const changePayType = (ptId: number) => {
    if (ptId === 11) {
      // 跳转到客服
      toServerUrl();
    } else if (ptId !== payTypeId) {
      setPayTypeId(ptId);
    }
  };

  const goPay = () => {
    if (amont > 0) {
      CreateOrder({
        TypeID: payTypeId,
        ProductID: pId,
        NeedReport: false,
        UT: userInfo?.Token,
      })
        .then((res: any) => {
          if (res?.Data) {
            // 跳转支付页
            toLink(res.Data);
          }
        })
        .catch(() => {});
    }
  };

  const _randDataItem = ({item}: {item: any}) => {
    switch (item.id) {
      case 'userinfo':
        return (
          <ObserverView themeStyle={{backgroundColor: 'color_23'}}>
            <View style={{padding: dpw12}}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                  <Avatar
                    style={{width: dpw66, height: dpw66, marginRight: dpw10}}
                  />
                  <View>
                    <ObserverText
                      tKey={userInfo?.NickName || ''}
                      type="model-title"
                    />
                    <ObserverText tKey={`ID: ${userInfo?.GameId || ''}`} />
                  </View>
                </View>
                <ObserverButton
                  style={{
                    paddingHorizontal: dpw12,
                    borderRadius: dpw40,
                    paddingVertical: dpw8,
                  }}
                  tKey="customerService"
                  type="primary"
                  onPress={toServerUrl}
                />
              </View>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  marginTop: dpw12,
                  marginBottom: dpw4,
                }}>
                <ObserverView
                  style={{
                    paddingHorizontal: dpw12,
                    paddingVertical: dpw10,
                    borderRadius: dpw4,
                    flex: 1,
                    flexDirection: 'row',
                    alignItems: 'center',
                    marginRight: dpw8,
                  }}
                  themeStyle={{backgroundColor: 'color_26'}}>
                  <Img
                    style={{width: dpw24, height: dpw24, marginRight: dpw16}}
                    url={coinPng}
                    isJoin={false}
                  />
                  <View>
                    <ObserverText
                      style={{fontWeight: 700}}
                      tKey={`${coin}`}
                      size="normal"
                    />
                    <ObserverText tKey="bookMoney" />
                  </View>
                </ObserverView>
                <ObserverView
                  style={{
                    paddingHorizontal: dpw12,
                    borderRadius: dpw4,
                    paddingVertical: dpw10,
                    flex: 1,
                    flexDirection: 'row',
                    alignItems: 'center',
                  }}
                  themeStyle={{backgroundColor: 'color_26'}}>
                  <Img
                    style={{width: dpw24, height: dpw24, marginRight: dpw16}}
                    url={coinPng}
                    isJoin={false}
                  />
                  <View>
                    <ObserverText
                      tKey={userInfo?.HasVip ? 'vip' : 'notVip'}
                      size="normal"
                      style={{fontWeight: 700}}
                    />
                    <ObserverText
                      themeStyle={{color: 'color_1'}}
                      tKey={userInfo?.HasVip ? 'validUntil' : ''}
                      tOptions={{
                        time: `${userInfo?.VipEndTime || ''}`.slice(0, 10),
                      }}
                    />
                  </View>
                </ObserverView>
              </View>
            </View>
          </ObserverView>
        );
      case 'topay':
        return (
          <View>
            <ModalHeader
              style={{marginHorizontal: dpw12}}
              title="bookRecharge"
              desc="purchased"
            />
            {Array.isArray(Read) && Read.length > 0 ? (
              <View
                style={{flexDirection: 'row', flexWrap: 'wrap', padding: dpw6}}>
                {Read.map(it => (
                  <ProductItem
                    key={it.Id}
                    {...it}
                    onPress={onSelectPay}
                    actId={pId}
                  />
                ))}
              </View>
            ) : (
              <Empty />
            )}
          </View>
        );
      case 'vip-topay':
        return (
          <View>
            <ModalHeader
              style={{marginHorizontal: dpw12}}
              title="vipPay"
              desc="purchased"
            />
            {Array.isArray(VIP) && VIP.length > 0 ? (
              <View
                style={{flexDirection: 'row', flexWrap: 'wrap', padding: dpw6}}>
                {VIP.map(it => (
                  <ProductItem
                    key={it.Id}
                    {...it}
                    onPress={onSelectPay}
                    actId={pId}
                  />
                ))}
              </View>
            ) : (
              <Empty />
            )}
          </View>
        );
      case 'topay-type':
        return (
          <View>
            <ModalHeader
              style={{marginHorizontal: dpw12}}
              title="paymentType"
            />
            {[
              ...payTypes,
              {
                Id: 11,
                TypeName: 'onlineServer',
                TypeDesc: 'serviceConsultation',
                IconUrl: '',
              },
            ].map((it: any) => (
              <ObserverView
                key={it.Id}
                style={{borderWidth: 1, paddingVertical: dpw10, margin: dpw12}}
                themeStyle={{
                  borderColor: payTypeId === it.Id ? 'color_1' : 'color_9',
                  backgroundColor: payTypeId === it.Id ? 'color_32' : 'color_2',
                }}>
                <TouchableOpacity
                  onPress={() => {
                    changePayType(it.Id);
                  }}
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}>
                  <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <Img
                      style={{
                        width: dpw24,
                        height: dpw24,
                        marginHorizontal: dpw10,
                      }}
                      url={it.IconUrl}
                      isJoin={false}
                    />
                    <ObserverText tKey={it.TypeName} />
                    <ObserverText
                      style={{marginLeft: dpw40}}
                      tKey={it.TypeDesc}
                      type="primary"
                    />
                  </View>
                </TouchableOpacity>
              </ObserverView>
            ))}
          </View>
        );
      case 'kind-tips':
        return (
          <ObserverView
            style={{padding: dpw12}}
            themeStyle={{backgroundColor: 'color_23'}}>
            <ObserverText
              style={{marginBottom: dpw12}}
              tKey="rechargeInstructions"
            />
            {kindTips.map(it => (
              <ObserverText
                style={{marginVertical: dpw4}}
                key={it.id}
                tKey={it.text}
                type="desc"
              />
            ))}
          </ObserverView>
        );
      default:
        return null;
    }
  };

  return (
    <ObserverView style={{flex: 1}}>
      <Header title="voucherCenter" navigation={navigation} />
      <View style={styles.con}>
        <FlatList
          data={list}
          renderItem={_randDataItem}
          keyExtractor={item => `${item.id}`}
        />
      </View>
      <View style={styles.pay}>
        <ObserverButton
          onPress={goPay}
          style={{borderRadius: 0}}
          tKey="immediatePayment"
          tOptions={{amont}}
          type="primary"
        />
      </View>
    </ObserverView>
  );
});

const styles = StyleSheet.create({
  con: {
    flex: 1,
    paddingBottom: dpw48,
  },
  pay: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
  },
});
export default ToPay;
